import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-08-24
 * Time: 20:35
 */
class MyTimerTask implements Comparable<MyTimerTask>{  //定时器任务
    private Runnable runnable;  //要执行的任务
    private long time;  //多久后执行
    public MyTimerTask(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay; //当前时间+延迟时间, 就是执行时间
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }

    //执行任务
    public void run(){
        runnable.run();
    }
    //获取执行的时间
    public long getTime(){
        return time;
    }
}
public class MyTimer {
    public Object locker = new Object();
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    public MyTimer(){
        //创建线程执行任务
        Thread t = new Thread(()->{
            try{
                while(true){
                    synchronized (locker){
                        MyTimerTask task = queue.peek();
                        while(task == null){
                            locker.wait();
                            task = queue.peek(); //重新看一下是否还是空, 因为线程调度是随机的. 有可能在这个线程调度之前有一个线程获取任务后就为空了
                        }
                        long curTime = System.currentTimeMillis();
                        if(curTime >= task.getTime()){
                            task.run();
                            queue.poll();
                        }else{
                            locker.wait(task.getTime() - curTime);
                        }


                    }
                }

            }catch (InterruptedException e){
                e.printStackTrace();
            }

        });
        t.start();
    }
    public void schedule(Runnable runnable, long delay){
        synchronized (locker){
            MyTimerTask task = new MyTimerTask(runnable, delay);
            queue.add(task);
            locker.notify(); //队列不为空, 可以让线程执行任务
        }


    }

    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(()->{
            System.out.println("hello 3000");
        }, 3000);
        myTimer.schedule(()->{
            System.out.println("hello 2000");
        }, 2000);
        myTimer.schedule(()->{
            System.out.println("hello 1000");
        }, 1000);
        Thread.sleep(4000);
        System.out.println("hello main");

    }
}
